import React, {
  useState,
  useRef,
  useEffect,
  useLayoutEffect,
  TouchEventHandler,
} from "react";
import "./index.scss";
import { Tag, Popup } from "antd-mobile";
import { DownOutline } from "antd-mobile-icons";
import { usePlayerStore } from "@/store/player";
type Props = {};
let duration = 0; //音频总时长
let barWidth = 0; //进度条可以走的最大距离
let beginW = 0; //按下dot时，当前innter的宽度
let beginX = 0; //按下dot时，手指与左侧屏幕边缘距离
const timeHandler = (second: number) => {
  let m = Math.floor(second / 60); //从秒数中提取分钟
  let s = Math.round(second % 60);
  let mStr = "";
  let sStr = "";
  if (m < 10) {
    mStr = "0";
  }
  if (s < 10) {
    sStr = "0";
  }
  return `${mStr}${m}:${sStr}${s}`;
};
export default function AudioPlay({}: Props) {
  const {
    popShow,
    togglePopShow,
    popData,
    isPlay,
    togglePlay,
    toggleBubbleShow,
  } = usePlayerStore((state) => state);
  const audioRef = useRef<HTMLAudioElement>(null);
  const barRef = useRef<HTMLDivElement>(null);
  const [move, setMove] = useState<number>(0); //进度条实时移动距离
  const [timeNow, setTimeNow] = useState<string>("00:00");
  const [timeMax, setTimeMax] = useState<string>("00:00");
  const handleCanPlay = () => {
    let ele = audioRef.current as HTMLAudioElement;
    let bar = barRef.current as HTMLDivElement;
    duration = ele.duration;
    // console.log("音频总时长", duration);
    barWidth = bar.offsetWidth; //获取进度条容器宽度
    setTimeMax(timeHandler(duration));
  };
  const handleTimeUpdate = () => {
    let ele = audioRef.current as HTMLAudioElement;
    let w = (ele.currentTime / duration) * barWidth;
    setMove(w);
    setTimeNow(timeHandler(ele.currentTime));
  };
  // 检测isPlay的变化，同步修改播放状态
  useEffect(() => {
    console.log("检测到了isPlay的变化");
    let ele = audioRef.current as HTMLAudioElement;
    if (!ele) return;
    if (isPlay) {
      ele.play(); //音频元素播放
    } else {
      ele.pause(); //音频元素暂停
    }
  }, [isPlay]);
  const handlePlay = (bool: boolean) => {
    togglePlay(bool); //修改按钮的播放状态
  };
  const handleStart: TouchEventHandler<HTMLDivElement> = (ev) => {
    // console.log("手指按下", ev);
    beginW = move;
    beginX = ev.changedTouches[0].clientX;
  };
  const handleMove: TouchEventHandler<HTMLDivElement> = (ev) => {
    // console.log("手指移动", ev);
    let ele = audioRef.current as HTMLAudioElement;
    let moveX = ev.changedTouches[0].clientX;
    let w = beginW + (moveX - beginX); //获取到的进度条宽度
    if (w <= barWidth) {
      setMove(w); //控制进度条
      // 控制音频  currentTime / duration = w / barWidth
      let current = (w / barWidth) * duration;
      ele.currentTime = current;
    }
  };
  const handleEnd: TouchEventHandler<HTMLDivElement> = () => {
    console.log("手指抬起");
  };
  return (
    <Popup
      visible={popShow}
      onMaskClick={() => {
        togglePopShow(false);
      }}
      bodyStyle={{ height: "100vh" }}
    >
      <div className="audio-play">
        {/* 播放器顶部 */}
        <div className="drop-cont">
          <DownOutline
            fontSize={20}
            onClick={() => {
              togglePopShow(false);
              toggleBubbleShow(true);
            }}
          />
          <Tag color="default">耀眼的播放器</Tag>
          <span></span>
        </div>
        {/* 播放暂停按钮 */}
        <div className={`play-btn ${isPlay ? "" : "stop"}`}>
          <i
            className="iconfont bofang_bg"
            onClick={() => {
              handlePlay(true);
            }}
          ></i>
          <i
            className="iconfont zanting1_bg"
            onClick={() => {
              handlePlay(false);
            }}
          ></i>
          <i className="iconfont zanting_bg"></i>
        </div>
        <div className="audio-control">
          <audio
            ref={audioRef}
            src={popData?.music}
            onCanPlay={handleCanPlay}
            onTimeUpdate={handleTimeUpdate}
          ></audio>
          <div className="icon-cont">
            <i className="iconfont jushoucang"></i>
            <i className="iconfont fenxiang"></i>
          </div>
          {/* 进度条 */}
          <div className="bar" ref={barRef}>
            <div className="inner" style={{ width: `${move}px` }}>
              <div
                className="dot"
                onTouchStart={handleStart}
                onTouchMove={handleMove}
                onTouchEnd={handleEnd}
              ></div>
            </div>
          </div>
          <div className="time-cont">
            <span>{timeNow}</span>
            <span>{timeMax}</span>
          </div>
        </div>
        <div className="circle circle1"></div>
        <div className="circle circle2"></div>
        <div className="circle circle3"></div>
      </div>
    </Popup>
  );
}
